﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text.RegularExpressions;
using DataBasetestApp.ServiceReference2;

namespace DataBasetestApp.Views
{
    public partial class RegistrationPage : PhoneApplicationPage
    {
        // Set up Variables
        int AddUserResult;

        public RegistrationPage()
        {
            InitializeComponent();
        }

        // Regeular expression for an email address
        static Regex ValidEmailRegex = CreateValidEmailRegex();

        // Method to create this Regular expression
        private static Regex CreateValidEmailRegex()
        {
            string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
                + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
                + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

            return new Regex(validEmailPattern, RegexOptions.IgnoreCase);
        }

        internal static bool EmailIsValid(string emailAddress)
        {
            bool isValid = ValidEmailRegex.IsMatch(emailAddress);

            return isValid;
        }

        // This happens when you try to submit details to the database
        private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            //EmailIsValid(emailBox.Text);

            // Check to see if any of teh fields are blank and if they are, don't let tehm past
            if (emailBox.Text == "" || usernameBox.Text == "" || passwordBox1.Password == "" || passwordBox2.Password == "" || teamCodeBox.Text == "")
            {
                MessageBox.Show("Please complete all fields.");
            }

            // Result of regular expression
            if (!(EmailIsValid(emailBox.Text)))
            {
                MessageBox.Show("Please enter a valid email address, as you will be notified via email when your registration is approved.");
            }
            else
            {
                // make sure the username is not less than 5 characters or over 15
                if (usernameBox.Text.Length < 5 || usernameBox.Text.Length > 15)
                {
                    MessageBox.Show("Username must be greater than 5 characters and may not contain any special characters");
                }

                else
                {
                    // make sure the password is not less than 5 characters or over 15
                    if (passwordBox1.Password.Length < 5 || usernameBox.Text.Length > 15)
                    {
                        MessageBox.Show("Password must be greater than 5 characters and may not contain any special characters");
                    }
                    else
                    {
                        // make sure that the two passwords are the same
                        if (passwordBox1.Password != passwordBox2.Password)
                        {
                            MessageBox.Show("Passwords do not match, please correct and try again.");
                        }

                        else
                        {
                            // send details to the database
                            string Email, Username, Password;
                            int teamCode;

                            Email = emailBox.Text;
                            Username = usernameBox.Text;
                            Password = passwordBox1.Password;
                            teamCode = Int32.Parse(teamCodeBox.Text);
                            GAALiveServiceClient client = new GAALiveServiceClient();
                            client.AddUserCompleted +=
                                new EventHandler<AddUserCompletedEventArgs>(client_AddUserCompleted);
                            client.AddUserAsync(Email, Username, Password, teamCode);
                        }
                    }
                }
            }
        }

        void client_AddUserCompleted(object sender, AddUserCompletedEventArgs a)
        {
            AddUserResult = a.Result;

            if (AddUserResult == 1)
            {
                MessageBox.Show("Registration Complete. You will be notified Via email when your registration is approved.");
                NavigationService.GoBack();
                //NavigationService.Navigate(new Uri("/Views/LoginPage.xaml", UriKind.Relative));
            }
            else if (AddUserResult == 0)
            {
                MessageBox.Show("Username already in use, please choose another.");
            }
            else if (AddUserResult == -1 || AddUserResult == 2)
            {
                MessageBox.Show("You have already registered, please try logging in.");
                NavigationService.GoBack();
            }
            else
                MessageBox.Show("Number returned = " + AddUserResult);
        }
    }
}